#include "PaletteShower/PaletteShower.h"
#include "PaletteExtraction/ColorSet.h"
#include "PaletteExtraction/ReduceColor.h"
#include <QApplication>
#include <QImage>
#include <QLabel>
#include <QDebug>
#include <QFileDialog>
#include <unordered_map>

int main(int argc, char** argv)
{
    QApplication a(argc, argv);

    qDebug() << "正在打开图片";

    auto path = QFileDialog::getOpenFileName();

    if(path.isEmpty())
    {
        qDebug() << "打开文件失败";
        return 0;
    }

    auto img = QImage(path);
    if(img.isNull())
    {
        qDebug() << "打开文件失败";
        return 0;
    }

    auto colorSet = ColorSet();
    qDebug() << "正在统计颜色";
    for(auto x = 0; x < img.width(); x++)
    {
        for(auto y = 0; y < img.height(); y++)
        {
            auto c = img.pixelColor(x, y);
            colorSet.AttachColor(Color(c.red(), c.green(), c.blue(), c.alpha()), 1);
        }
    }
    qDebug() << "正在提取色盘";
    Palette palette;
    std::unordered_map<Color, uint32_t> map;
    ReduceColor::MCAReduce(colorSet, {}, palette, map);

    qDebug() << "显示色盘";
    PaletteShower w;
    w.setPalette(palette);
    w.setWindowTitle("色盘");
    w.updateImage();
    w.show();

    qDebug() << "显示原图";
    QLabel w2;
    w2.setPixmap(QPixmap::fromImage(img));
    w2.setWindowTitle("原图");
    w2.show();

    qDebug() << "显示索引化的图片";
    QLabel w3;
    auto img2 = img.copy();
    for(auto x = 0; x < img2.width(); x++)
    {
        for(auto y = 0; y < img2.height(); y++)
        {
            auto c = img2.pixelColor(x, y);
            auto new_c = palette[map[Color(c.red(), c.green(), c.blue(), c.alpha())]];
            img2.setPixelColor(x, y, QColor(new_c.r, new_c.g, new_c.b, new_c.a));
        }
    }
    w3.setPixmap(QPixmap::fromImage(img2));
    w3.setWindowTitle("索引化图");
    w3.show();

    return a.exec();
}
